/********************************************************************
Name: 
Author: Dan Thompson
Date: September 2021
Description: 

********************************************************************/

clear all
set matsize 11000
set maxvar 15000
gl path = "~/Dropbox/Mariel Effects"

* Bring in the county level analysis data
use "$path/Replication/data/county_analysis_data.dta", clear
keep if rank<=251
tsset rank year
tempfile data
save `data'

* Set up a matrix to store the effect and placebo estimates
matrix Output = J(22,555,.)

* Loop over Miami and the 555 control counties and construct synthetic controls
* for each to compute the main synth estimate and placebo synth estimates 
local c = 0
sum rank
local num = r(max)
qui forval i=1/`num' {
	
	* Bring in the data
	use `data', clear
	if `i'!=1 drop if rank==1
	
	* Skip this county if it doesn't have data
	sum rank if rank==`i'
	if `r(N)'==0 continue
	
	* Create the synthetic control
	synth rep_vs rep_vs(1960) rep_vs(1964) rep_vs(1968) rep_vs(1972) rep_vs(1976), ///
		trunit(`i') trperiod(1980)
	
	* Call the output into some matrices
	matrix Treat = e(Y_treated)
	matrix Synth = e(Y_synthetic)
	
	* Put the treatment and control output into the Output matrix
	local ++c
	forval r = 1/11 {
		matrix Output[`r',`c'] = Treat[`r',1]
		local j = `r' + 11
		matrix Output[`j',`c'] = Synth[`r',1]
	}
	
	* Print a status update
	noi di "`i' of `num'"
}

* Call the synthetic control method output back into memory
clear
svmat Output
rename Output* Y*
drop if Y1==.

* Put treatment and synthetic control side by side and compute the difference
gen year = 1960 + 4*mod(_n-1, 11)
gen treat = _n<=11
rename Y* Y*_
reshape wide Y*_, i(year) j(treat)
rename (Y*_1 Y*_0) (treat* synth*)
reshape long treat synth, i(year) j(id)
gen diff = treat - synth

* Save the formatted output to a data set
save "$path/Replication/modified_data/synth_output250.dta", replace
